import { Footer } from '@/components';
import { getFakeCaptcha } from '@/services/apis/login';
import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { Helmet, history, useModel, useNavigate } from '@umijs/max';
import { Alert, message, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import Settings from '../../../../config/defaultSettings';
import { login } from '@/services/apis/companyRegister';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});

const ActionIcons = () => {
  const { styles } = useStyles();

  return (
    <>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action} />
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action} />
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action} />
    </>
  );
};

// const Lang = () => {
//   const { styles } = useStyles();

//   return (
//     <div className={styles.lang} data-lang>
//       {SelectLang && <SelectLang />}
//     </div>
//   );
// };

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<any>({});
  const { initialState, setInitialState } = useModel('@@initialState');
  const navigate = useNavigate();
  const { styles } = useStyles();
  // const intl = useIntl();
  const enumType: any = {
    enterpise: "companyName",
    service: "username",
    city: "departmentName",
    county: "departmentName",
    rate: "departmentName",
    audit: "departmentName",
    accept: "departmentName"
  }
  const fetchUserInfo = async (msg: any) => {

    if (msg) {

      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: { name: msg[enumType[msg["userType"]]], access: msg.userType, data: msg },
        }));
      });
    } else {
      const cacheMgs = JSON.parse(sessionStorage.getItem("data") as any)
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: { name: cacheMgs[enumType[cacheMgs["userType"]]], access: cacheMgs.userType, data: cacheMgs },
        }));
      });
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      values.password = values.password?.trim()
      const { code, data,msg } = await login({ ...values });
      if (code == '0') {
        // //message.success('登录成功！');
        sessionStorage.setItem("access", data.userType)
        sessionStorage.setItem("data", JSON.stringify(data))

        // setInitialState(prev => ({ ...prev, settings: Settings as any,currentUser: { name: data[enumType[data["userType"]]], access: data.userType } }))
        await fetchUserInfo(data);
        setTimeout(() => {
          if (data.userType.includes("enterpise")) {
            
            navigate('/digitalization_manager');

          } else if (data.userType.includes("service")) {
            navigate('/product_of_mine');

          } else if (data.userType.includes("city")) {
            navigate('/index_page');
          } else if (data.userType.includes("county")) {
            navigate('/index_page');
          } else if (data.userType.includes("rate") || data.userType.includes("audit") || data.userType.includes("accept")) {
            navigate('/work_of_rating');
          } 
          
          // else if (data.userType.includes("audit")) {
          //   history.push('/work_of_audit');
          // } else if (data.userType.includes("accept")) {
          //   history.push('/work_of_acceptance');
          // }
        }, 500)

        return;
      } else {
        setUserLoginState({ status: "error", text: msg });

      }
    } catch (error) {
      setUserLoginState({ status: "error", text: "登录失败，请重试" });
    }
  };
  const { status, text } = userLoginState;

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          登录页
          {Settings.title && ` - ${Settings.title}`}
        </title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="丽水市中小企业数字化转型服务平台"
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs
            activeKey={"account"}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码登录',
              },
            ]}
          />

          {status === 'error' && (
            <LoginMessage content={text} />
          )}

          <ProFormText
            name="username"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined />,
            }}
            placeholder={'请输入用户名'}
            rules={[
              {
                required: true,
                message: '请输入用户名!',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined />,
            }}
            placeholder={'请输入密码'}
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />


          <div
            style={{
              marginBottom: 40,
            }}
          >
            <a
              style={{
                float: 'left',
              }}
              onClick={() => { history.push("/company_register") }}
            >
              企业注册
            </a>
            <a
              style={{
                float: 'right',
              }}
              onClick={() => { history.push("/service_provide_register") }}
            >
              服务商注册
            </a>
          </div>
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
